<template>
  <input type="tel" placeholder="请输入手机号" v-model="phoneNumber" @input="validatePhoneNumber"
         class="input text-sm input-bordered"/>
</template>

<script setup>

const props = defineProps({
  modelValue: String,
})

const emit = defineEmits(['update:modelValue'])
const phoneNumber = ref('');

watch(() => props.modelValue, (newVal, oldVal) => {
  // 这里可以根据需要对父组件传递的值做出相应的处理
  phoneNumber.value = newVal
})

function validatePhoneNumber(event) {
  const value = event.target.value;
  const newValue = value.replace(/\D/g, ''); // 只允许数字
  if (newValue.length > 11) {
    phoneNumber.value = newValue.slice(0, 11); // 手机号码最多11位
  } else {
    phoneNumber.value = newValue;
  }
  event.target.value = phoneNumber.value; // 更新input的值
  emit('update:modelValue', phoneNumber.value)
}
</script>

<style scoped>

</style>